<template>
    <v-col class="pa-4 fill-height d-flex flex-column">
        <v-toolbar flat color="surface">
            <v-toolbar-title>好友请求</v-toolbar-title>
        </v-toolbar>

        <v-divider />

        <v-container fluid class="py-4" style="overflow-y: auto;">
            <div v-if="requests.length" class="d-flex flex-column" style="gap: 12px;">
                <v-card v-for="req in requests" :key="req.requestId" outlined elevation="1" :title="req.senderName">
                </v-card>
            </div>

            <div v-else class="text-medium-emphasis text-center mt-10">
                暂无好友请求
            </div>
        </v-container>
    </v-col>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import axios from 'axios'

const currentUserId = Number(localStorage.getItem('user_id'))
const token = localStorage.getItem('jwt_token')

const requests = ref<{
    senderName: string
    requestId: number
    senderId: number
    recipientId: number
    createdAt: string
}[]>([])

async function fetchRequests() {
    try {
        const res = await axios.get(
            `http://localhost:8080/api/friends/getApply/${currentUserId}`,
            {
                headers: {
                    Authorization: `Bearer ${token}`
                },
                auth: {
                    username: 'admin',
                    password: '123456'
                }
            }
        )
        requests.value = res.data
    } catch (err) {
        console.error('❌ 加载好友请求失败', err)
    }
}

async function handleAccept(requestId: number) {
    try {
        await axios.post(
            `http://localhost:8080/api/friends/accept`,
            null,
            {
                params: { requestId },
                headers: { Authorization: `Bearer ${token}` },
                auth: { username: 'admin', password: '123456' }
            }
        )
        alert('✅ 已接受好友请求')
        await fetchRequests()
    } catch (err) {
        console.error('❌ 接受失败', err)
        alert('❌ 接受失败')
    }
}

async function handleReject(requestId: number) {
    try {
        await axios.post(
            `http://localhost:8080/api/friends/reject`,
            null,
            {
                params: { requestId },
                headers: { Authorization: `Bearer ${token}` },
                auth: { username: 'admin', password: '123456' }
            }
        )
        alert('✅ 已拒绝好友请求')
        await fetchRequests()
    } catch (err) {
        console.error('❌ 拒绝失败', err)
        alert('❌ 拒绝失败')
    }
}

function formatTime(isoStr: string) {
    const date = new Date(isoStr)
    return date.toLocaleString()
}

onMounted(fetchRequests)
</script>
